import { ref, reactive, shallowRef } from 'vue'
import * as echarts from 'echarts'
import getInitOption from '../options/TotalFlowOption'
import { getTotalFlowColor } from '../utils/totalFlowColorUtils'
import { getColor } from '../utils/colorUtils'
import { queryInitApi } from '../api/pipeline'

const chartInstance = shallowRef() // 图表实例
const allTotalFlowData = reactive([]) // 数据
const yData = reactive([]) // y轴数据
const currentPipelineId = ref() // 图表配置
const titleFontSize = ref(0) // 图表字体大小
const totalFlowRef = shallowRef()

async function queryInitPipelineId() {
  const { data: res } = await queryInitApi()
  currentPipelineId.value = res.data.id
}

function registerTotalFlow(totalFlow) {
  totalFlowRef.value = totalFlow
}
function initChart() {
  chartInstance.value = echarts.init(totalFlowRef.value, 'dark')
  chartInstance.value.setOption(getInitOption())
}
function screenAdapter() {
  titleFontSize.value = (totalFlowRef.value.offsetWidth / 100) * 4
  const barWidth = titleFontSize.value * 3
  const borderRadiusWidth = barWidth / 2
  const apdaterOption = {
    xAxis: {
      nameTextStyle: {
        fontSize: titleFontSize.value * 0.75
      }
    },
    series: [
      {
        itemStyle: {
          borderRadius: [0, borderRadiusWidth, borderRadiusWidth, 0]
        },
        barWidth: barWidth
      }
    ]
  }
  chartInstance.value.setOption(apdaterOption)
  chartInstance.value.resize()
}
function updateTotalFlow(time, data, status) {
  const totalFlowData = {
    value: data,
    itemStyle: {
      color: status === 1 ? getTotalFlowColor(currentPipelineId.value - 1) : getColor(0)
    }
  }
  yData[0] = time
  allTotalFlowData[0] = totalFlowData
  updateTotalFlowChart()
}
function updateTotalFlowChart() {
  const dataOption = {
    yAxis: {
      data: yData
    },
    series: [
      {
        data: allTotalFlowData
      }
    ]
  }
  chartInstance.value.setOption(dataOption)
}

export const useTotalFlow = () => {
  return {
    registerTotalFlow,
    initChart,
    screenAdapter,
    updateTotalFlow,
    currentPipelineId,
    queryInitPipelineId
  }
}
